/*
 * Copyright (c) 2010, Tess Snider

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

using System;
using System.Collections.Generic;

namespace DesertPaintLab
{
	public partial class SimulatorWindow : Gtk.Window
	{
		PlayerProfile profile;
		Gtk.ListStore recipeData = new Gtk.ListStore(typeof(string), typeof(int));

		public SimulatorWindow(PlayerProfile profile) : base(Gtk.WindowType.Toplevel)
		{
			this.profile = profile;
			this.Build ();
			
			Gtk.TreeViewColumn reagentColumn = new Gtk.TreeViewColumn();
			Gtk.CellRendererText reagentColumnCell = new Gtk.CellRendererText();
			reagentColumn.PackStart(reagentColumnCell, true);		
			reagentColumn.Title = "Ingredient";
			
			reagentListView.AppendColumn(reagentColumn);
			reagentColumn.AddAttribute(reagentColumnCell, "text", 0);
			
			reagentListView.Model = ReagentManager.NameListModel;
			
			Gtk.TreeViewColumn additiveColumn = new Gtk.TreeViewColumn();
			Gtk.CellRendererText additiveColumnCell = new Gtk.CellRendererText();
			additiveColumn.PackStart(additiveColumnCell, true);		
			additiveColumn.Title = "Ingredient";
			
			recipeView.AppendColumn(additiveColumn);
			additiveColumn.AddAttribute(additiveColumnCell, "text", 0);
			
			Gtk.TreeViewColumn qtyColumn = new Gtk.TreeViewColumn();
			Gtk.CellRendererText qtyColumnCell = new Gtk.CellRendererText();
			qtyColumnCell.Editable = true;
			qtyColumnCell.Edited += OnQtyEdited;
			qtyColumn.PackStart(qtyColumnCell, true);		
			qtyColumn.Title = "Qty";
			
			recipeView.AppendColumn(qtyColumn);
			qtyColumn.AddAttribute(qtyColumnCell, "text", 1);
			
			recipeView.Model = recipeData;
			
			recipeData.RowChanged += OnRecipeChanged;
			recipeData.RowDeleted += OnRecipeChanged;
			recipeData.RowInserted += OnRecipeChanged;
			recipeData.RowsReordered += OnRecipeChanged;
			
		}
		
		protected virtual void OnAddReagent(object sender, System.EventArgs e)
		{
			Gtk.TreeModel model;
			Gtk.TreeIter iter;

			Gtk.TreeSelection selection = reagentListView.Selection;
			if ((selection != null) && selection.GetSelected(out model, out iter))
			{					
				recipeData.AppendValues(model.GetValue(iter, 0).ToString(), 1);	
				
				recipeData.IterNthChild(out iter, recipeView.Children.Length - 1);
				
				selection = recipeView.Selection;
				selection.SelectIter(iter);
			} 
		}	
		
		protected void OnQtyEdited(object sender, Gtk.EditedArgs args)
        {
			Gtk.TreeIter iter;
			recipeData.GetIter(out iter, new Gtk.TreePath(args.Path));
			
			int oldValue = (int)recipeData.GetValue(iter, 1);
			
            try
            {
                recipeData.SetValue(iter, 1, int.Parse(args.NewText));
				UpdateRecipeColor();
            }
            catch (Exception)
            {
            	recipeData.SetValue(iter, 1, oldValue);
			}
        }	
	
		protected void OnRecipeChanged(object sender, GLib.SignalArgs args)
	    {
			UpdateRecipeColor();
	    }	

		void UpdateRecipeColor()
		{
			if (recipeView.Children.Length == 0)
			{
				paintSwatch.Clear();
			}
			
			Reaction reaction;
			Gtk.TreeIter iter;
			string reagentName;
			int qty;
			PaintColor color = null;
			Reagent reagent = null;
			
			int baseRedSum = 0;
			int baseGreenSum = 0;
			int baseBlueSum = 0;
			
			int reactRedSum = 0;
			int reactGreenSum = 0;
			int reactBlueSum = 0;
			
			int pigmentCount = 0;
			
			SortedDictionary<string,bool> reagentSet = new SortedDictionary<string,bool>();
			List<Reagent> reagents = new List<Reagent>();
			
			recipeData.GetIterFirst(out iter);
			
			do
			{
   				reagentName = (string) recipeData.GetValue(iter, 0);
				
				if (reagentName == null)
				{
					continue;	
				}
				
				qty = (int)recipeData.GetValue(iter, 1);
				reagent = ReagentManager.GetReagent(reagentName);
				if (!reagent.IsCatalyst)
				{
					color = reagent.Color;
					baseRedSum += qty * color.Red;
					baseGreenSum += qty * color.Green;
					baseBlueSum += qty * color.Blue;
					pigmentCount += qty;
				}
				if (!reagentSet.ContainsKey(reagentName) && reagentSet.Count <= 4)
				{
					reagentSet[reagentName] = true;
					// Run reactions.
					foreach (Reagent otherReagent in reagents)
					{
						reaction = profile.FindReaction(otherReagent, reagent);
						if (reaction != null)
						{
							reactRedSum += reaction.Red;
							reactGreenSum += reaction.Green;
							reactBlueSum += reaction.Blue;
						}
					}
					reagents.Add(reagent);
				}
				
			}
			while (recipeData.IterNext(ref iter));
			
			paintSwatch.Color = new PaintColor(
				CalculateColor(baseRedSum, pigmentCount, reactRedSum),
			    CalculateColor(baseGreenSum, pigmentCount, reactGreenSum),
				CalculateColor(baseBlueSum,  pigmentCount, reactBlueSum));	
		}
		
		byte CalculateColor(int baseSum, int pigmentCount, int reactSum)
		{
			return (byte)Math.Max(Math.Min(Math.Round((((float)baseSum / (float)pigmentCount) + (float)reactSum)), 255), 0);
		}

		protected virtual void OnIncrementReagent (object sender, System.EventArgs e)
		{
			Gtk.TreeModel model;
			Gtk.TreeIter iter;

			Gtk.TreeSelection selection = recipeView.Selection;
			if ((selection != null) && selection.GetSelected(out model, out iter))
			{
				int oldValue = (int)recipeData.GetValue(iter, 1);
				recipeData.SetValue(iter, 1, oldValue + 1);
			}
			
		}
		
		protected virtual void OnDecrementReagent (object sender, System.EventArgs e)
		{
			Gtk.TreeModel model;
			Gtk.TreeIter iter;

			Gtk.TreeSelection selection = recipeView.Selection;
			if ((selection != null) && selection.GetSelected(out model, out iter))
			{
				int oldValue = (int)recipeData.GetValue(iter, 1);
				if (oldValue == 1)
				{
					recipeData.Remove(ref iter);
				}
				else
				{
					recipeData.SetValue(iter, 1, oldValue - 1);
				}
			}			
			
		}

	}
}